package se.su.dsv.theclient;

import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

/* TODO: Start the service to keep track of peers.
 * TODO: Fix all Intents
 * TODO: Do Shit
 */

public class TheClient extends ListActivity {
	private ListAdapter mAdapter;
	private ISocialService m_service;
	private boolean serviceBound = false;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		//bssid = ((WifiManager) getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getBSSID();
		//ipAddress = ((WifiManager)getSystemService(Context.WIFI_SERVICE)).getConnectionInfo().getIpAddress();
		startServiceBackground();
		if (!serviceBound) {
			bindService();
		}
		
		Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
		startManagingCursor(c);

		String[] columns = new String[] {People.NAME};
		int[] names = new int[] {R.id.row_entry};

		mAdapter = new SimpleCursorAdapter(this, R.layout.main, c, columns, names);
		setListAdapter(mAdapter);
		getListView().setTextFilterEnabled(true);

	}
	
	private void bindService() {
    	serviceBound = bindService(new Intent(this, SocialService.class), serviceConnection, Context.BIND_AUTO_CREATE);
	}
	
    private void startServiceBackground(){
    	startService(new Intent(this, SocialService.class));
    }
   
    private void killBackgroundService(){
    	stopService(new Intent(this, SocialService.class));
    }

    private ServiceConnection serviceConnection = new ServiceConnection(){

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			Toast.makeText(TheClient.this, R.string.service_connected, Toast.LENGTH_SHORT).show();
			m_service = ISocialService.Stub.asInterface(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			Toast.makeText(TheClient.this, R.string.service_disconnected, Toast.LENGTH_SHORT).show();		
		}
    	
    };
    
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent i = new Intent(this, SocialVenueList.class);
		Cursor c = (Cursor) mAdapter.getItem(position);
		long phoneId = c.getLong(c.getColumnIndex(People.PRIMARY_PHONE_ID));
		i.setData(Uri.withAppendedPath(Phones.CONTENT_URI, Long.toString(phoneId)));
//		i.putExtra("Venues", m_service.getVenueList("all", venues));
//		i.putExtra("Activities", m_service.getActivityList(venue, activities));
		//bindService();
		startActivity(i);
	}

}
